import { Injectable } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { ApesMessageService } from '@shared/apes/message';
import { UploadFile } from '@shared/apes/upload';

@Injectable({
  providedIn: 'root',
})
export class HtmlToCanvasService {

  constructor(private apiService: ApiService,
              private msg: ApesMessageService,
  ) {
  }

  htmlToCanvas(param, file) {
    console.log(param);
    let setData = {
      url: param.url,  //https://cdn.91autoparts.com/epc/ford/200824/CF_B02010.png
      option: param,
    };
    this.imgToBase64(setData, file);
  }


  private imgToBase64(setData, callBack) {
    let api = 'image.to.base64';
    this.apiService.post(api, { url: setData.url }).subscribe((body) => {
      if (body) {
        let currentImg = 'data:image/png;base64,' + body;
        let snName = '';
        let name = setData.option.name;
        if (setData.option.hasOwnProperty('points')) {
          setData.option.points.forEach((points) => {
            snName += '-sn:' + points['sn'];
          });
        }
        let fileName = name + snName;
        this.imgToURL(currentImg, setData).then((dataUrl) => {
          let file = HtmlToCanvasService.ImgDataURLtoFile(dataUrl, fileName);
          this.uploadFile(file).then((f) => {
            callBack(f);
          });
        });
      } else {
        this.msg.error('图片转换失败！');
      }
    });
  }

  private imgToURL(currentImg, setData): Promise<string> {
    return new Promise(resolve => {
      const canvas = document.createElement('canvas');
      document.body.appendChild(canvas);
      const ctx = canvas.getContext('2d');
      const img = new Image();
      img.src = currentImg;
      img.onload = () => {
        try {
          canvas.width = img.width;
          canvas.height = img.height;
          ctx.drawImage(img, 0, 0);
          ctx.strokeStyle = 'red';
          //{w: '27', x: '38', h: '16', y: '104', sn: 'HB1', activate: true},
          //{w: '45', x: '24', h: '16', y: '195', sn: '3K155'}
          // ctx.strokeRect(24, 195, 45, 16);
          if (setData.option.hasOwnProperty('points')) {
            setData.option.points.forEach((points) => {
              ctx.strokeRect(points.x, points.y, points.w, points.h);
            });
          }
        } catch {
        }
        const dataURL = canvas.toDataURL();
        document.body.removeChild(canvas);
        resolve(dataURL);
      };
    });

  }

  private static ImgDataURLtoFile(dataUrl, fileName) {
    let arr = dataUrl.split(',');
    let mime = arr[0].match(/:(.*?);/)[1];
    let bstr = atob(arr[1]);
    let n = bstr.length;
    let u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], fileName, { type: mime });
  }

  _fileList: UploadFile[] = [];
  imgType: any = 'image/png,image/jpeg,image/gif,image/bmp';

  get fileList(): UploadFile[] {
    return this._fileList || [];
  }

  set fileList(input: UploadFile[]) {
    let value = input;
    if (this._fileList === value) {
      return;
    }
    this._fileList = value;
  }

  private uploadFile(file): Promise<string> {
    return new Promise(resolve => {
      let api = 'fileserver/upload';
      let fileList = [file];
      // fileList.push(file);
      this.apiService.upload(fileList, api).subscribe(
        (event: any) => {
          const returnFile = event.body;
          const callBack = this.showFilesList(returnFile);
          resolve(callBack);
          // this.msg.success('上传成功');
        },
        err => {
          console.log(err);
          // this.msg.error('上传失败');
        },
      );
    });
  }

  /** 处理上传文件 **/
  private showFilesList(returnFile): any {
    let tempFileList = [];
    returnFile.map((file) => {
      if (!file.url && file.id && this.imgType.indexOf(file.type) > -1) {
        file.url = 'fileserver/view/' + file.id;
      }
      tempFileList.push(file);
    });
    // console.log(tempFileList);
    return tempFileList;
  }

}
